#!/bin/sh

# =============================================================================
# OpenFOAM 结果可视化脚本
# 支持多种输出格式：PNG, EPS, PDF, SVG
# =============================================================================

# 默认配置
OUTPUT_FORMAT=${1:-png}
FILENAME_BASE="planarPoiseuille"
SKIP_LINES=4

# 彩色输出函数
print_info() { printf "\033[32m[INFO]\033[0m %s\n" "$1"; }
print_error() { printf "\033[31m[ERROR]\033[0m %s\n" "$1" >&2; }
print_warn() { printf "\033[33m[WARN]\033[0m %s\n" "$1" >&2; }

# 检查输入文件
if [ ! -f "../postProcessing/probes/0/U" ]; then
    print_error "OpenFOAM probe data not found: ../postProcessing/probes/0/U"
    exit 1
fi

if [ ! -f "../WatersKing.dat" ]; then
    print_warn "Analytical solution data not found: ../WatersKing.dat"
    print_warn "Will plot only numerical results"
    PLOT_ANALYTICAL=false
else
    PLOT_ANALYTICAL=true
fi

# 提取数值数据
print_info "Extracting numerical data..."
tail -n +$SKIP_LINES ../postProcessing/probes/0/U | \
    tr -s " " | tr -d '(' | cut -d " " -f1-2 > ../Numerical.dat

DATA_POINTS=$(wc -l < ../Numerical.dat)
print_info "Extracted $DATA_POINTS data points"

# 检查 gnuplot
if ! command -v gnuplot >/dev/null 2>&1; then
    print_error "gnuplot not found - please install gnuplot"
    exit 1
fi

# 设置输出格式
case $OUTPUT_FORMAT in
    png)
        TERMINAL="pngcairo enhanced color font 'Helvetica,16' size 1000,750 linewidth 2"
        OUTPUT_FILE="${FILENAME_BASE}.png"
        FONT_SIZE=18
        ;;
    eps)
        TERMINAL="postscript eps color enhanced 'Helvetica,20'"
        OUTPUT_FILE="${FILENAME_BASE}.eps"
        FONT_SIZE=24
        ;;
    pdf)
        TERMINAL="pdfcairo enhanced color font 'Helvetica,12' size 8,6"
        OUTPUT_FILE="${FILENAME_BASE}.pdf"
        FONT_SIZE=14
        ;;
    svg)
        TERMINAL="svg enhanced size 1000,750 font 'Helvetica,14'"
        OUTPUT_FILE="${FILENAME_BASE}.svg"
        FONT_SIZE=16
        ;;
    *)
        print_error "Unsupported format: $OUTPUT_FORMAT"
        print_error "Supported formats: png, eps, pdf, svg"
        exit 1
        ;;
esac

print_info "Generating $OUTPUT_FORMAT format: $OUTPUT_FILE"

# 构造 gnuplot 脚本模板（不展开变量）
GP_SCRIPT=$(cat <<'TPL'
set terminal TERMINAL_REPL
set output "OUTPUT_REPL"
set xlabel "Time / [s]" font "Helvetica,FONT_REPL"
set ylabel "Velocity / [m/s]" font "Helvetica,FONT_REPL"
set title "TITLE_TEXT_REPL" font "Helvetica,TITLE_REPL"
set grid
set key right bottom
set xrange [0:25]
set yrange [0:8]
PLOT_CMD_REPL
TPL
)

# 根据是否有解析解决定标题与绘图命令
if [ "$PLOT_ANALYTICAL" = true ]; then
    TITLE_TEXT="Planar Poiseuille Flow: Numerical vs Analytical"
    PLOT_CMD='plot "../Numerical.dat" t "OpenFOAM (every 100 pts)" with linespoints pointinterval 100 lt 1 pt 6 ps 1.5, "../WatersKing.dat" with lines t "Analytical" lt -1'
else
    TITLE_TEXT="Planar Poiseuille Flow: Numerical Result"
    PLOT_CMD='plot "../Numerical.dat" t "OpenFOAM (every 100 pts)" with linespoints pointinterval 100 lt 1 pt 6 ps 1.5'
fi

# 将变量安全替换进脚本
GP_SCRIPT=$(printf "%s" "$GP_SCRIPT" \
    | sed "s|TERMINAL_REPL|$TERMINAL|g" \
    | sed "s|OUTPUT_REPL|$OUTPUT_FILE|g" \
    | sed "s|FONT_REPL|$FONT_SIZE|g" \
    | sed "s|TITLE_REPL|$((FONT_SIZE-2))|g" \
    | sed "s|TITLE_TEXT_REPL|$TITLE_TEXT|g" \
    | sed "s|PLOT_CMD_REPL|$PLOT_CMD|g")

# 执行 gnuplot（静默模式）
printf "%s\n" "$GP_SCRIPT" | gnuplot >/dev/null 2>&1

# 结果检查
if [ -f "$OUTPUT_FILE" ]; then
    print_info "Graph saved successfully: $OUTPUT_FILE"
else
    print_error "Failed to generate graph"
    exit 1
fi

#------------------------------------------------------------------------------
